package com

import (
	"fmt"
	"reflect"
	"sanguo/cluster"
	"sanguo/codec/cs"
	"sanguo/node/common/IDGen"
	ss_msg "sanguo/protocol/ss/message"

	"github.com/golang/protobuf/proto"
)

const (
	TeamMaxRoleCount = 3   //队伍最大人数
	HeartBeatTimeout = 60  //队伍心跳超时
	ApplyMaxTime     = 300 //申请消息超时时间
	OffLineKickTime  = 60  //玩家离线后在队保留时间
	FightInviteTime  = 60  //战斗邀请时间
	MatchRoleCount   = 3   //匹配人数
)

//状态
const (
	RoleStatus_Online  = 1
	RoleStatus_Offline = 2
	TeamStatus_Safe    = 1
	TeamStatus_Battle  = 2
)

//角色类型
const (
	RoleType_Player = 1
	RoleType_Robot  = 2
)

//入队申请处理
const (
	AcceptApply_AutoAgree    = 1
	AcceptApply_AutoDisagree = 2
	AcceptApply_Request      = 3
)

var (
	encoder     *cs.Encoder
	selfService cluster.Service

	teamGen  *IDGen.IDGenerator
	matchGen *IDGen.IDGenerator
)

func GetSelfService() cluster.Service {
	return selfService
}

/////////////////////
func SendToClient(game cluster.PeerID, userID string, msg proto.Message) {
	relayMsg := &ss_msg.Relay{
		Users: make([]string, 1)[0:0],
	}
	relayMsg.Users = append(relayMsg.Users, userID)
	relayMsg.MsgType = proto.String(reflect.TypeOf(msg).String())
	bytes, err := encoder.EnCode(cs.NewMessage(0, msg))
	if nil == err {
		relayMsg.Msg = bytes.Bytes()
		cluster.PostMessage(game, relayMsg)
	}
}

func TeamGenID() (uint64, error) {
	if nil == teamGen {
		return 0, fmt.Errorf("nil == teamgen")
	}
	return teamGen.Gen()
}

func MatchGenID() (uint64, error) {
	if nil == matchGen {
		return 0, fmt.Errorf("nil == matchGen")
	}
	return matchGen.Gen()
}

func Init(selfService_ cluster.Service) bool {

	selfService = selfService_
	/*
	* 数字无依据
	 */
	areaID := 10
	serverID := 10

	matchGen = IDGen.New(uint16(areaID), byte(serverID))
	teamGen = IDGen.New(uint16(areaID), byte(serverID))

	return matchGen != nil && teamGen != nil
}

func init() {
	encoder = cs.NewEncoder("sc")
}
